package zheezes.socket.impl.gd;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import zheezes.protocol.PacketAnalyzer;
import zheezes.protocol.impl.gd.GdMasterAddr;
import zheezes.socket.PostOffice;
import zheezes.util.ByteUtil;
import zheezes.util.IntUtil;


public class GdPostOffice extends PostOffice {
	private static Logger logger = Logger.getLogger(GdPostOffice.class);
	
	public GdPostOffice() {
	}
	
	public GdPostOffice(String host, int port, String msas, String pwd, PacketAnalyzer packetAnalyzer) {
		List<GdMasterAddr> list = new ArrayList<GdMasterAddr>();
		for (String s : msas.split(",")) {
			GdMasterAddr msa = new GdMasterAddr((byte) IntUtil.parse(s.trim()));
			list.add(msa);
		}
		init(host, port, list, pwd, packetAnalyzer);
	}

	public GdPostOffice(String host, int port, List<GdMasterAddr> msas,	String pwd, PacketAnalyzer packetAnalyzer) {
		init(host, port, msas, pwd, packetAnalyzer);
	}
	
	private void init(String host, int port, List<GdMasterAddr> msas, String pwd, PacketAnalyzer packetAnalyzer) {
		logger.debug(String.format("connect host = %s, port = %d", host, port));
		for (GdMasterAddr msa : msas) {
			GdPostman postman = new GdPostman(msa);
			postman.setHost(host);
			postman.setPort(port);
			postman.setPwd(ByteUtil.stoa(pwd.toCharArray()));
			postman.setPacketAnalyzer(packetAnalyzer);
			postmen.add(postman);
		}
	}
}
